package com.wayhome.srpingbootmybatis.fileimportmanager.bo.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.wayhome.srpingbootmybatis.excel.Dr9225AccessInfo;
import com.wayhome.srpingbootmybatis.exception.CustomerException;
import com.wayhome.srpingbootmybatis.fileimportmanager.dto.ImportFileRlstDTO;
import com.wayhome.srpingbootmybatis.fileimportmanager.dto.ImportSetlReqContent;
import com.wayhome.srpingbootmybatis.fileimportmanager.enums.MedTypeEnum;
import com.wayhome.srpingbootmybatis.mbs.util.HeadContentCellStyle;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service("setlInfoVerifyImportHandler")
public class SetlInfoVerifyImportHandler extends AbstractImportHandler<ImportSetlReqContent> {

    private static final String CSP_PATH = "info-verify/setl";

    private static final String FILE_PATH = "/Users/liangcai/Desktop/opt/ylbzj/info-verify-import/";

    private static final String TEMPLATE_CSP_PATH = "template";

    private static final String TEMPLATE_FILE_NAME = "信息核查-结算信息批量导入模版.xlsx";

    @Override
    protected void readFileAndUpload(MultipartFile multipartFile, ImportFileRlstDTO importFileRlstDTO) throws Exception {
        long maxSize = 5 * 1024 * 1024;
        long size = multipartFile.getSize();
        if (size > maxSize) {
            throw new RuntimeException("上传文件不能大于5M");
        }
        InputStream inputStream = multipartFile.getInputStream();
        ReadImportFileListener listener = new ReadImportFileListener();
        EasyExcel.read(inputStream, ImportSetlReqContent.class, listener).sheet().doRead();
        if (listener.getSuccessCnt() == 0 && listener.getFailCnt() == 0) {
            throw new CustomerException("没有解析出要导入的数据");
        }
        String filePath = defaultUploadFile(CSP_PATH, FILE_PATH, listener.successList, listener.errorList);
        //设置成功条数
        importFileRlstDTO.setSuccessCnt(listener.getSuccessCnt());
        //设置失败条数
        importFileRlstDTO.setFailCnt(listener.getFailCnt());
        //设置上传文件路径
        importFileRlstDTO.setFilePath(filePath);
        String importMemo = "上传完成，总条数：" + (importFileRlstDTO.getSuccessCnt() + importFileRlstDTO.getFailCnt()) +"条,成功" + importFileRlstDTO.getSuccessCnt() +"条，失败" + importFileRlstDTO.getFailCnt() + "条";
        importFileRlstDTO.setImportMemo(importMemo);
    }

    @Override
    protected String getBusinessMemo() {
        return "信息核查-结算信息查询-批量查询功能上传的文件";
    }

    @Override
    public void downloadImportFile(String fileName, String filePath, String newFileName) throws Exception {
        HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
        String serverFileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        cspService.download(response,BUCKET,serverFileName,CSP_PATH, fileName);
    }

    @Override
    public void downloadTemplate() throws Exception {
        HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
        cspService.download(response,BUCKET,TEMPLATE_FILE_NAME, TEMPLATE_CSP_PATH, TEMPLATE_FILE_NAME);
    }

    private class ReadImportFileListener extends AnalysisEventListener<ImportSetlReqContent> {
        //成功条数
        private final List<ImportSetlReqContent> successList = new ArrayList<>();
        //失败条数
        private final List<ImportSetlReqContent> errorList = new ArrayList<>();

        public int getSuccessCnt() {
            return successList.size();
        }

        public int getFailCnt() {
            return errorList.size();
        }

        private int importCnt = 0;

        @Override
        public void invoke(ImportSetlReqContent content, AnalysisContext analysisContext) {
            boolean successFlag = true;
            StringBuilder memoBuilder = new StringBuilder();
            if (StringUtils.isEmpty(content.getPtanName())) {
                memoBuilder.append("姓名是必传项，不能为空；");
                successFlag = false;
            }
            if (StringUtils.isEmpty(content.getCertno())) {
                memoBuilder.append("证件号码是必传项，不能为空；");
                successFlag = false;
            }
            if (StringUtils.isEmpty(content.getStartTime()) || StringUtils.isEmpty(content.getEndTime())) {
                memoBuilder.append("查询结算的开始结束时间是必填项，不能为空；");
                successFlag = false;
            } else if (!canCover2Date(content.getStartTime()) || !canCover2Date(content.getEndTime())){
                memoBuilder.append("查询时间格式错误，请按照YYYY-MM-DD格式传;");
                successFlag = false;
            }
            if (StringUtils.isEmpty(content.getMedType())) {
                memoBuilder.append("医疗类别是必填项，不能为空");
                successFlag = false;
            }
            if (StringUtils.isEmpty(MedTypeEnum.getCodeByMsg(content.getMedType()))) {
                memoBuilder.append("医疗类别是传递不正确;");
                successFlag = false;
            }
            if (successFlag) {
                content.setMemo("success");
                successList.add(content);
            } else {
                String memo = memoBuilder.toString();
                content.setMemo(memo);
                errorList.add(content);
            }
            importCnt ++;
            if (importCnt > 1000) {
                throw new RuntimeException("最大查询条数不能超过1000条");
            }
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            log.info("==========>导入文件,解析数据完成");
        }
    }

}
